package com.innovation.ic.sc.web.controller.sc;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.sc.base.pojo.constant.Constants;
import com.innovation.ic.sc.base.pojo.variable.ApiResult;
import com.innovation.ic.sc.base.pojo.variable.AuthenticationUser;
import com.innovation.ic.sc.base.pojo.variable.ServiceResult;
import com.innovation.ic.sc.base.vo.cms.AccountBindBySmsVo;
import com.innovation.ic.sc.web.controller.AbstractController;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @desc   短信验证码controller
 * @author linuo
 * @time   2022年8月5日10:30:57
 */
@Api(value = "短信验证码API", tags = "SmsInfoController")
@RestController
@RequestMapping("/api/v1/smsInfo")
@DefaultProperties(defaultFallback = "defaultFallback")
public class SmsInfoController extends AbstractController {
    private static final Logger logger = LoggerFactory.getLogger(SmsInfoController.class);

    /**
     * 发送短信验证码
     * @param mobile 手机号
     * @return 返回发送短信验证码结果
     */
    @HystrixCommand
    @ApiOperation(value = "发送短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String"),
    })
    @RequestMapping(value = "/send/{mobile}", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> send(HttpServletRequest request, HttpServletResponse response, @PathVariable("mobile") String mobile) {
        ApiResult<JSONObject> apiResult;
        if (!StringUtils.validateParameter(mobile)) {
            String message = "调用接口【/api/v1/smsInfo/send】时，参数mobile不能为空";
            logger.warn(message);
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 判断当前手机号是否格式正确
        boolean judgeResult = Validator.isMobile(mobile);
        if(!judgeResult){
            String message = "手机号格式有误";
            logger.warn(message);
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 通过ERP发送短信验证码
        ServiceResult<JSONObject> result = smsInfoService.sendSmsCodeByErp(mobile);
        if (result.getSuccess().equals(Boolean.FALSE)){
            apiResult = new ApiResult<>();
            apiResult.setSuccess(result.getSuccess());
            apiResult.setCode(ApiResult.PHONE_CODE_EXPIRE);
            apiResult.setMessage(result.getMessage());
            return new ResponseEntity<>(apiResult, HttpStatus.OK);
        }

        apiResult = new ApiResult<>();
        apiResult.setSuccess(result.getResult().getBoolean(Constants.RESULT));
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result.getMessage());
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 绑定账号
     * @param accountBindBySmsVo 账号绑定的Vo类
     * @return 返回绑定结果
     */
    @HystrixCommand
    @ApiOperation(value = "绑定账号")
    @ApiImplicitParam(name = "AccountBindBySmsVo", value = "账号绑定的Vo类", required = true, dataType = "AccountBindBySmsVo")
    @RequestMapping(value = "/bindAccount", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> bindAccount(@RequestBody AccountBindBySmsVo accountBindBySmsVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ApiResult<JSONObject> apiResult;
        if (!StringUtils.validateParameter(accountBindBySmsVo.getUserName()) || !StringUtils.validateParameter(accountBindBySmsVo.getPassWord()) ||
                !StringUtils.validateParameter(accountBindBySmsVo.getPhoneNum()) || !StringUtils.validateParameter(accountBindBySmsVo.getCode())) {
            String message = "调用接口【/api/v1/smsInfo/bindAccount】时，参数userName、passWord、phoneNum和code不能为空";
            logger.warn(message);
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 判断当前手机号是否格式正确
        boolean judgeResult = Validator.isMobile(accountBindBySmsVo.getPhoneNum());
        if(!judgeResult){
            String message = "手机号格式有误";
            logger.warn(message);
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(HttpStatus.BAD_REQUEST.value());
            apiResult.setMessage(message);
            return new ResponseEntity<>(apiResult, HttpStatus.BAD_REQUEST);
        }

        // 绑定账号
        ServiceResult<JSONObject> result = smsInfoService.bindAccount(accountBindBySmsVo);

        apiResult = new ApiResult<>();
        apiResult.setSuccess(result.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result.getMessage());
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }

    /**
     * 解绑账号
     * @return 返回解绑结果
     */
    @HystrixCommand
    @ApiOperation(value = "解绑账号")
    @RequestMapping(value = "/unBindAccount", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ResponseEntity<ApiResult> unBindAccount(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ApiResult<Boolean> apiResult;

        AuthenticationUser authenticationUser = this.getAuthenticationUser(request);
        if (null == authenticationUser){
            apiResult = new ApiResult<>();
            apiResult.setSuccess(Boolean.FALSE);
            apiResult.setCode(ApiResult.TOKEN_ILLEGAL_EXPIRE);
            return new ResponseEntity(apiResult, HttpStatus.UNAUTHORIZED);
        }

        // 解绑账号
        ServiceResult<Boolean> result = smsInfoService.unBindAccount(authenticationUser);

        apiResult = new ApiResult<>();
        apiResult.setSuccess(result.getSuccess());
        apiResult.setCode(HttpStatus.OK.value());
        apiResult.setMessage(result.getMessage());
        apiResult.setResult(result.getResult());
        return new ResponseEntity<>(apiResult, HttpStatus.OK);
    }
}